﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CommonCompareTool
{
    public class CompareRank
    {
        List<CompareItem> items = new List<CompareItem>();

        internal void SetResult(ComparePair x)
        {
            switch (x.Result)
            {
                case CompareResult.UnCompared:
                    break;
                case CompareResult.Equal:
                    break;
                case CompareResult.FirstOneIsBetter:
                    Record(x.ItemA, 1);
                    break;
                case CompareResult.LastOneIsBetter:
                    Record(x.ItemB, 1);
                    break;
                case CompareResult.BothLike:
                    Record(x.ItemA, 1);
                    Record(x.ItemB, 1);
                    break;
                case CompareResult.BothDisLike:
                    Record(x.ItemA, -1);
                    Record(x.ItemB, -1);
                    break;
                default:
                    break;
            }



        }

        private void Record(CompareItem compareItem, int p)
        {
            CompareItem item = GetItem(compareItem.Item);
            item.Point += p;
        }

        private CompareItem GetItem(string p)
        {
            var o = from x in items where x.Item == p select x;

            if (o.Count<CompareItem>()<=0)
            {
                CompareItem item=new CompareItem() {Item=p,Point=0 };
                
                items.Add(item);
                
                return item;
            }

            return o.ToList<CompareItem>()[0];
        }

        public override string ToString()
        {
            var list=items.OrderByDescending<CompareItem, int>(x => x.Point).ToList<CompareItem>();

            StringBuilder sbd = new StringBuilder();

            list.ForEach(x => sbd.Append(x.Item + "[ " + x.Point.ToString() + " ]" + "\r\n"));

            return sbd.ToString();

        }
    }
}
